package com.campus.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 */
public class HttpClientUtil {

    static final  int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     * @param url Get请求的基础URL
     * @param paramMap Get请求的参数，会被拼接到URL查询字符串部分，例如 ?key=value&key2=value2
     * @return
     */
    public static String doGet(String url, Map<String, String> paramMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try{
            URIBuilder builder = new URIBuilder(url); // URIBuilder：用于动态构建 URL，尤其适用于包含多个参数的场景。
            if(paramMap != null) {
                // 遍历并拼接接参数
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap POST 请求的参数列表。这些参数将会以表单的形式（键值对）发送到服务器。
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 初始化结果变量和相应变量
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList(); // NameValuePair：表示一个简单的键值对（例如表单中的一个字段和值）。
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 将参数列表 paramList 转换为 UrlEncodedFormEntity，用于模拟表单提交。它将参数以 application/x-www-form-urlencoded 格式编码。
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost4Json(String url, Map<String, String> paramMap, Map<String, String> headers) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            if (headers != null) {
                headers.forEach(httpPost::setHeader);
            }

            // 设置请求体内容
            if (paramMap != null && paramMap.containsKey("json")) {
                StringEntity entity = new StringEntity(paramMap.get("json"), "utf-8");
                entity.setContentEncoding("utf-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发起Post请求并处理流式响应
     * @param url
     * @param paramMap
     * @param headers
     * @return
     * @throws IOException
     */
    public static InputStream doPost4JsonStream(String url, Map<String, String> paramMap, Map<String, String> headers) throws IOException {
        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            // 创建 Http Post 请求
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            if (headers != null) {
                headers.forEach(httpPost::setHeader);
            }

            // 设置请求体内容
            if (paramMap != null && paramMap.containsKey("json")) {
                StringEntity entity = new StringEntity(paramMap.get("json"), "utf-8");
                entity.setContentEncoding("utf-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行 HTTP 请求
            response = httpClient.execute(httpPost);

            // 返回流式响应
            return response.getEntity().getContent();
        } catch (Exception e) {
            if (response != null) {
                response.close();
            }
            throw e;
        }
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC) // 设置连接超时
                .setConnectionRequestTimeout(TIMEOUT_MSEC) // 设置请求获取连接的超时时间
                .setSocketTimeout(TIMEOUT_MSEC).build(); // 设置读取数据的超时时间
    }

}
